//
//  PHAssetCollection+Ex.m
//  PhotoKit
//
//  Created by Guo Rui on 2017/10/12.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "PHAssetCollection+Ex.h"
#import "PHPhotoLibrary+Ex.h"

@implementation PHAssetCollection (Ex)

+ (void)saveCamerRollWithImage:(UIImage *)image completion:(void (^)(PHAsset *asset,NSError *error))completion
{
    if (!image) {
        if (completion) {
            NSError *error = [NSError errorWithDomain:@"cn.photo.errordomian" code:0 userInfo:nil];
            completion(nil, error);
        }
        return;
    }
    
    __block NSString *ID = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
       PHAssetChangeRequest *request = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        ID = request.placeholderForCreatedAsset.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (!error) {
            PHFetchOptions *options = [[PHFetchOptions alloc] init];
            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[ID] options:options].firstObject;
            if (completion) {
                completion(asset, nil);
            }
        }
        else {
            if (completion) {
                completion(nil, error);
            }
        }
    }];
}

+ (PHAsset *)saveCamerRollWithImage:(UIImage *)image error:(NSError *__autoreleasing *)error
{
    if (!image) {
        *error = [NSError errorWithDomain:@"cn.photo.errordomian" code:0 userInfo:nil];
        return nil;
    }
    
    __block NSString *ID = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        PHAssetChangeRequest *request = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        ID = request.placeholderForCreatedAsset.localIdentifier;
    } error:error];
    
    if (!(*error)) {
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[ID] options:options].firstObject;
        return asset;
    }
    
    return nil;
}

+ (void)saveImage:(UIImage *)image toCollectionWithTitle:(NSString *)title error:(NSError *__autoreleasing *)error
{
    // 1. 获取资源对象
    PHAsset *asset = [PHAssetCollection saveCamerRollWithImage:image error:error];
    if (*error) {
        return;
    }
    
    // 2. 获取相册
    PHAssetCollection *collection = [PHPhotoLibrary createPHAssetCollectionWithTitle:title error:error];
    if (*error) {
        return;
    }
    
    // 3. 将图片保存到这个相册的第一个位置上
    [collection saveAsset:asset error:error];
}


+ (instancetype)fetchCustomCollectionWithTitle:(NSString *)title
{
    if (title == nil || title.length == 0) {
        return nil;
    }
    
    PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    PHAssetCollection *searchCollection = nil;
    for (PHAssetCollection *collection in result) {
        if ([collection.localizedTitle isEqualToString:title]) {
            searchCollection = collection;
        }
    }
    
    return searchCollection;
}

- (void)saveAsset:(PHAsset *)asset error:(NSError *__autoreleasing *)error
{
    if (asset == nil) {
        *error = [NSError errorWithDomain:@"cn.photo.errordomian" code:0 userInfo:nil];
        return;
    }
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:self];
        // 插入到第一个位置
        [request insertAssets:@[asset] atIndexes:[NSIndexSet indexSetWithIndex:0]];
    } error:error];
}

- (void)saveImage:(UIImage *)image error:(NSError *__autoreleasing *)error
{
    if (image == nil) {
        *error = [NSError errorWithDomain:@"cn.photo.errordomian" code:0 userInfo:nil];
        return;
    }

    PHAsset *asset = [PHAssetCollection saveCamerRollWithImage:image error:error];
    if (*error != nil) {
        [self saveAsset:asset error:error];
    }
}

@end
